//
//  UIImage+addition.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/12.
//  Copyright © 2018年 imf. All rights reserved.
//

import Foundation
import UIKit

extension UIImage {
    
    func reSizeImage(reSize:CGSize)-> UIImage {
        //UIGraphicsBeginImageContext(reSize);
        UIGraphicsBeginImageContextWithOptions(reSize,false,UIScreen.main.scale)
        self.draw(in: CGRect(x: 0, y: 0, width: reSize.width, height: reSize.height))
        let reSizeImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return reSizeImage
    }
    
    static func zipImage(currentImage: UIImage, scaleSize:CGFloat,percent: CGFloat) -> Data{
        //压缩图片尺寸
        UIGraphicsBeginImageContext(CGSize(width: currentImage.size.width*scaleSize, height: currentImage.size.height*scaleSize))
        currentImage.draw(in: CGRect(x: 0, y: 0, width: currentImage.size.width*scaleSize, height:currentImage.size.height*scaleSize))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        //高保真压缩图片质量
        //UIImageJPEGRepresentation此方法可将图片压缩，但是图片质量基本不变，第二个参数即图片质量参数。
        let imageData  = UIImageJPEGRepresentation(newImage, percent) ?? Data()
        return imageData
    }
    
    func imageWithTintColor(tintColor: UIColor) -> UIImage? {
       return self.imageWithTintColor(tintColor: tintColor, blendMode: CGBlendMode.destinationIn)
    }
    
    class func createImageWithColor(color: UIColor) -> UIImage? {
        let rect: CGRect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context: CGContext? = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image;
    }
    
    private func imageWithTintColor(tintColor: UIColor, blendMode: CGBlendMode) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0);
        tintColor.setFill()
        let bounds = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        UIRectFill(bounds);
        
        //Draw the tinted image in context
        self.draw(in: bounds, blendMode: blendMode, alpha: 1.0)
        
        if (blendMode != CGBlendMode.destinationIn) {
            self.draw(in: bounds, blendMode: CGBlendMode.destinationIn, alpha: 1.0)
        }
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return tintedImage;
    }
}
